package cn.changeforyou.demo.netty.common;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhyu
 * @date 2021/3/18 9:01
 */
@Sharable
public class YbkjWebsocketDataEncodeHandler extends ChannelOutboundHandlerAdapter {

    Logger log = LoggerFactory.getLogger(YbkjWebsocketDataEncodeHandler.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("msg 类型:{}", msg.getClass().getCanonicalName());
        }
        if (msg instanceof DefaultFullHttpResponse) {
            log.info("有用户建立了webSocket 协议");
        } else if (msg instanceof CloseWebSocketFrame) {
            log.info("服务端关闭了webSocket 协议");
        } else if (msg instanceof Data) {
            msg = new TextWebSocketFrame(JsonUtils.toJson(msg));
        }
        super.write(ctx, msg, promise);
    }
}
